<?php

class Accounts extends Model {

	function Accounts() {
		parent::Model();
	}

	function create( $department_id, $user, $password, $first_name, $last_name, $email ) {
		$sql = 'insert into `accounts`(`department_id`, `user`, '
			.'`password`, `first_name`, `last_name`, `email`, `last_login`, `is_activ`, `is_manager`, `is_admin`)'
			.'values(?, ?, md5(?), ?, ?, ?, now(), 1, 0, 0)';
		$this->db->query($sql, array($department_id, $user, 
			$password, $first_name, $last_name, $email) );
	}

	function fetch( $account_id ) {
		$sql =  'select * from `accounts` where `account_id`=?';
		$r = $this->db->query($sql, array($account_id));
		return $r->row();
	}

	function switch_manager( $account_id ) {
		$account = $this->fetch($account_id);
		if( $account->is_manager ) {
			$sql = 'update `accounts` set `is_manager`=0 where `account_id`=?';
		} else {
			$sql = 'update `accounts` set `is_manager`=1 where `account_id`=?';
		}
		$this->db->query( $sql, array($account_id));
	}

	function fetch_by_department( $department_id ) {
		$sql = 'select * from `accounts` where `department_id`=?';
		$r = $this->db->query($sql, array($department_id));
		return $r->result();
	}

	function fetch_by_project( $project_id ) {
		$sql = 'select a.* from `accounts` a, `accounts_projects` ap '
			.'where ap.project_id = ? and ap.account_id = a.account_id';
		$r = $this->db->query($sql, array($project_id));
		return $r->result();
	}


	function fetch_all() {
		$sql = 'select * from `accounts`';
		$r = $this->db->query($sql);
		return $r->result();
	}

	function remove( $account_id ) {
		$sql = 'delete from `accounts` where `account_id`=?';
		$this->db->query($sql, array($account_id));	
	}

}

?>
